import type { ApiEnvelope, BomRecordApi, PageResponse, BomSearchParams, BomCreatePayload, BomEditPayload } from '../types/bom';

// 通用属性数组构建：按照 definitions 排序，读取 values
export function buildBomAttributes(defs: any[] = [], values: Record<string, any> = {}) {
  return defs.map((d: any, idx: number) => {
    // 修复：正确处理属性值的键映射
    // d.code 是属性定义的代码（如 p_123），d.name/d.propertyName 是属性名
    const propCode = d.code || d.propertyName;
    let propValue: any = '';
    // 优先使用 code 查找，再尝试用 name
    if(propCode && propCode in values) {
      propValue = values[propCode];
    } else if(d.name && d.name in values) {
      propValue = values[d.name];
    } else if(d.propertyName && d.propertyName in values) {
      propValue = values[d.propertyName];
    }
    return {
      propertyName: d.name || d.propertyName || d.code,
      propertyValue: propValue == null ? '' : propValue,
      sort: typeof d.sortId === 'number' ? d.sortId : (typeof d.sort === 'number' ? d.sort : idx + 1)
    };
  });
}

// 统一编辑 body 构建：传入前端 payload（来自 BomSimpleEntryDialog 或其它页面）
export function buildBomEditBody(payload: any): BomEditPayload & { attributes: ReturnType<typeof buildBomAttributes>; feeModel: 'fixed' | 'count'; feeAmount: number } {
  const defs = payload.attributeDefinitions || [];
  const vals = payload.attributeValues || {};
  const attributes = buildBomAttributes(defs, vals);
  const feeModel: 'fixed' | 'count' = payload.costMode === 'count' ? 'count' : 'fixed';
  const feeAmount = feeModel === 'fixed' ? (payload.fixedAmount ?? payload.unitPrice ?? 0) : (payload.unitPrice ?? payload.fixedAmount ?? 0);
  return {
    id: payload.id,
    classId: payload.classId, // 若新增时为字符串，也可在调用处转换
    className: payload.materialCategory, // 页面保证为名称
    productType: payload.productType,
    name: payload.costName,
    bomType: payload.bomType,
    attributes,
    feeModel,
    feeAmount
  } as any;
}
import http from './http';

// 使用后端规范：POST /api/bom/search  Body: { page,pageSize,invCode,invName,className,productType }
export async function fetchBomList(params: BomSearchParams) {
  const { page = 1, pageSize = 10, invCode = '', invName = '', className = '', productType = '' } = params || {};
  const body = { page, pageSize, invCode, invName, className, productType };
  const envelope = await http.post<ApiEnvelope<PageResponse<BomRecordApi>>>('/api/bom/search', body);
  // 拦截器返回的就是 ApiEnvelope
  if ((envelope as any).code !== 200) throw new Error((envelope as any).msg || 'BOM查询失败');
  return (envelope as any).data;
}

// 新增 BOM 条目
// 注意：后端返回格式为 {code: 200, data: "<bomId>", msg: ""}，data 是 BOM 的 ID（字符串，避免数字精度丢失）
export async function addBom(payload: BomCreatePayload) {
  const envelope = await http.post<ApiEnvelope<string>>('/api/bom/add', payload);
  if ((envelope as any).code !== 200) throw new Error((envelope as any).msg || '新增BOM失败');
  // 返回 ID 值（字符串），调用方可直接使用
  return (envelope as any).data;
}

// 编辑 BOM 条目
export async function editBom(payload: BomEditPayload) {
  const envelope = await http.post<ApiEnvelope<Record<string, any>>>('/api/bom/edit', payload);
  if ((envelope as any).code !== 200) throw new Error((envelope as any).msg || '编辑BOM失败');
  return (envelope as any).data;
}
